package cuongnh.project.japanesediary.vocabulary.ui.view.action.menucontribution.category.kanjis;

import java.util.Set;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import cuongnh.project.japanesediary.vocabulary.common.CommonServices;
import cuongnh.project.japanesediary.vocabulary.model.Category;
import cuongnh.project.japanesediary.vocabulary.model.Kanji;
import cuongnh.project.japanesediary.vocabulary.ui.dialog.AddRelatedKanjiDialog;
import cuongnh.project.japanesediary.vocabulary.ui.view.CategoryKanjisView;

public class AddCategoryKanjiAction implements IViewActionDelegate {

	public static final String ID = "cuongnh.project.japanesediary.vocabulary.action.AddCategoryKanji";

	protected IViewPart m_view;
	
	protected TableViewer tableViewer;

	private CommonServices commonServices;

	private Category category;
	
	private Set<Kanji> selectedKanjis;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
	 */
	@Override
	public void init(IViewPart view) {
		m_view = view;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		// 履歴ビュー更新
		CategoryKanjisView view = (CategoryKanjisView) m_view
				.getAdapter(CategoryKanjisView.class);
		commonServices = view.getCommonServices();
		category = view.getSelectedCategory();
		AddRelatedKanjiDialog relatedKanjiDialog = new AddRelatedKanjiDialog(
				view.getSite().getShell(), commonServices);
		if (relatedKanjiDialog.open() == Window.OK) {
			selectedKanjis = relatedKanjiDialog.getSelectedKanjis();
			if (!selectedKanjis.isEmpty()) {
				// update selected vocabulary to current category
				Category currentCategory = commonServices.getCategoryDao()
						.getCategoryWithKanjis(category.getCategoryId());
				currentCategory.getKanjis().addAll(selectedKanjis);
				commonServices.getCategoryDao().update(currentCategory);
			}
		}
		view.update();
		tableViewer = view.getTblvKanjis();
		tableViewer.setSelection(new StructuredSelection(selectedKanjis.toArray()));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
	 * .IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {

	}

}
